<template>
  <div class="advert-board-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <div class="filter-list flex-c">
        <template v-for="(item, i) in filterItem" :key="i">
          <div class="filter-item">
            <template v-if="item.type == 'input_keyword'">
              <filterKeyword :currentItem="item" @search="searchKeyword($event, item)" />
            </template>
            <template v-else-if="item.key == 'portfolioIds'">
              <PortfolioIdsMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select_multiple'">
              <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
            </template>
            <template v-else-if="item.type == 'select'">
              <a-select v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear @change="setSearchVal">
                <a-option v-for="(option, s) in item.optionItems" :key="s" :value="option.value" :label="option.label" />
              </a-select>
            </template>
            <template v-else-if="item.type == 'date_range'">
              <a-range-picker v-model="item.value" :="item.attrs" :disabledDate="disabledDate" :style="{ width: item.width + 'px' }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" @change="setSearchVal" />
            </template>
          </div>
        </template>
        <div class="filter-item">
          <a-button @click="resetAll">重置</a-button>
        </div>
      </div>

      <div class="filter-result" v-show="resultTags.length > 0">
        <a-space wrap>
          <a-tag v-for="item in resultTags" size="small" color="arcoblue" :closable="!['currencyCode', 'date'].includes(item.key)" :key="item.key" @close="delTag(item)">
            <template v-if="!(item.tagVal instanceof Array && item.tagVal.length > 2)">
              <span> {{ item.label }}：</span>
              <p>{{ item.tagVal instanceof Array ? item.tagVal?.join(',') : item.tagVal }}</p>
            </template>
            <a-popover v-else position="bottom">
              <div class="flex-c">
                <span> {{ item.label }}：</span>
                <p>{{ item.tagVal[0] }}，{{ item.tagVal[1] }}等{{ item.tagVal.length }}项</p>
              </div>
              <template #content>
                <p v-for="(val, j) in item.tagVal" :key="j">{{ val }}</p>
              </template>
            </a-popover>
          </a-tag>

          <a-button type="text" style="color: #000430" v-if="resultTags.length > 2" size="mini" @click="resetAll">清除全部</a-button>
        </a-space>
      </div>
    </div>
    <div class="time-w flex-c" v-show="searchParam.startDate">
      <p style="margin-right: 20px">环比周期：{{ targetMap.momStartDate }}至{{ targetMap.momEndDate }}</p>
      <p>年同比周期：{{ targetMap.yoyStartDate }}至{{ targetMap.yoyEndDate }}</p>
    </div>
    <a-spin class="chart-wrap" :loading="loading" v-show="searchParam.startDate" style="width: 100%">
      <!-- 图表 -->
      <BoardChart ref="boardChartRef" :targetMap="targetMap" :searchParams="searchParam" />
      <!-- 广告贡献情况 -->
      <ContributionBoardChart ref="contributionBoardChartRef" :targetMap="targetMap" :searchParams="searchParam" />
      <a-row class="grid-demo" :gutter="10">
        <a-col :span="8">
          <!-- 转化率漏洞 -->
          <AdFunnelChart ref="adFunnelChartRef" :targetMap="targetMap" />
        </a-col>
        <a-col :span="8">
          <!-- ACoS排行 -->
          <AcosRankList ref="acosRankListRef" :searchParams="searchParam" />
        </a-col>
        <a-col :span="8">
          <!-- RoAS排行 -->
          <RoasRankList ref="roasRankListRef" :searchParams="searchParam" />
        </a-col>
      </a-row>
      <a-row class="grid-demo" :gutter="10">
        <a-col :span="12">
          <!-- 广告花费排行榜 -->
          <CostRankList ref="costRankListRef" :searchParams="searchParam" />
        </a-col>
        <a-col :span="12">
          <!-- 广告销售额TOP20 -->
          <SaleRankList ref="saleRankListRef" :searchParams="searchParam" />
        </a-col>
      </a-row>
      <!-- 广告活动关键词TOP20 -->
      <KeywordRankList ref="keywordRankListRef" :searchParams="searchParam" />
    </a-spin>

    <div class="error-w" v-show="!searchParam.startDate">
      <a-empty> 数据量过大，请选择时间缩小查询范围 </a-empty>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import selectMultiple from '@/components/Form/selectMultiple.vue'
  import PortfolioIdsMultiple from '../campaign/components/portfolioIdsMultiple.vue'
  import BoardChart from './components/boardChart.vue'
  import AdFunnelChart from './components/adFunnelChart.vue'
  import AcosRankList from './components/acosRankList.vue'
  import RoasRankList from './components/roasRankList.vue'
  import CostRankList from './components/costRankList.vue'
  import SaleRankList from './components/saleRankList.vue'
  import KeywordRankList from './components/keywordRankList.vue'
  import ContributionBoardChart from './components/contributionBoardChart.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { currencySymbol } from '@/utils/globalData'
  import { getOverallMetrics } from '@/api/advert'
  import { getStartAndEndTime, rangeShortcuts } from '../common'
  import dayjs from 'dayjs'
  onMounted(() => {
    getShopList()
    getMarketList()
    getUserList()
    setSearchVal()
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplaceIds',
      label: '站点',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopIds',
      label: '全部店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'currencyCode',
      label: '货币',
      value: ref('USD'),
      type: 'select',
      width: 100,
      optionItems: Object.keys(currencySymbol).map((key: string) => {
        return {
          value: key,
          label: key,
        }
      }),
    },
    {
      key: 'adTypes',
      label: '广告类型',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [
        {
          label: '商品广告',
          value: 'SPONSORED_PRODUCTS',
        },
        {
          label: '品牌广告',
          value: 'SPONSORED_BRANDS',
        },
        {
          label: '展示广告',
          value: 'SPONSORED_DISPLAY',
        },
      ],
    },
    {
      key: 'portfolioIds',
      label: '广告组合',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'ownerIds',
      label: '销售员',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'date',
      label: '日期',
      value: ref(getStartAndEndTime('last_30_days')),
      type: 'date_range',
      width: 240,
      attrs: {
        placeholder: ['开始日期', '结束日期'],
      },
    },
    {
      type: 'input_keyword',
      key: 'asin',
      keyItems: [
        { label: 'ASIN', value: 'asin' },
        { label: '父ASIN', value: 'parentAsin' },
        { label: 'MSKU', value: 'sku' },
      ],
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: false,
    },
  ])
  const resultTags = ref<any>([])
  const searchParam = ref<any>({})
  const adFunnelChartRef = ref()
  const boardChartRef = ref()
  const acosRankListRef = ref()
  const roasRankListRef = ref()
  const costRankListRef = ref()
  const saleRankListRef = ref()
  const keywordRankListRef = ref()
  const loading = ref(false)

  const contributionBoardChartRef = ref()
  const useBaseData = useBaseDataStore()
  const shopList = ref<Array<any>>([])
  const targetMap = ref<any>({})

  //禁用时间
  function disabledDate(current: any) {
    return dayjs(current).isAfter(dayjs().subtract(1, 'day'))
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    shopList.value = useBaseData.shopList
    filterItem.value[1].optionItems = useBaseData.shopList?.map((el: any) => {
      return {
        label: el.shopName,
        value: el.id,
      }
    })
  }
  // 获取站点
  async function getMarketList() {
    await useBaseData.getMarketList()
    filterItem.value[0].optionItems = useBaseData.markedtList?.map((el: any) => {
      return {
        label: el.marketplaceName,
        value: el.marketplaceId,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[5].optionItems = useBaseData.userList?.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }

  //查询图表和表格数据
  async function startSearch() {
    if (!searchParam.value.startDate) return
    loading.value = true
    await getTargetList()
    loading.value = false
    nextTick(() => {
      boardChartRef.value.refreshData()
      contributionBoardChartRef.value.refreshData()
      adFunnelChartRef.value.refreshData()
      acosRankListRef.value.refreshData()
      roasRankListRef.value.refreshData()
      costRankListRef.value.refreshData()
      saleRankListRef.value.refreshData()
      keywordRankListRef.value.refreshData()
    })
  }
  // 获取所有指标概览数据
  async function getTargetList() {
    if (!searchParam.value.startDate) return
    const res: any = await getOverallMetrics(searchParam.value)
    targetMap.value = res?.data || {}
  }
  function searchKeyword(searchVal: any, item: any) {
    item.key = searchVal.code
    item.label = searchVal.label
    item.value = searchVal.value
    setSearchVal()
  }
  // 批量选择数据
  function selectMulVal(searchVal: any, item: any) {
    item.value = searchVal
    setSearchVal()
  }
  function setSearchVal() {
    setResultTags()
    searchParam.value = {}
    filterItem.value.forEach((el: FilterTableItem) => {
      if (el.key == 'date') {
        searchParam.value.startDate = el.value?.[0]
        searchParam.value.endDate = el.value?.[1]
      } else if (el.key === 'portfolioIds' && el.value instanceof Array) {
        searchParam.value.portfolioIds = el.value.map((el: any) => el.portfolioId)
      } else {
        searchParam.value[el.key] = el.value
      }
    })
    startSearch()
  }

  function setResultTags() {
    resultTags.value = []
    filterItem.value.forEach((el: FilterTableItem) => {
      let val: any = el.value
      let noVal = val === '' || val === null || val === undefined || (val instanceof Array && val.length === 0)
      if (!noVal) {
        resultTags.value.push({
          ...el,
          tagVal: getTagVal(el),
        })
      }
    })
  }
  // 获取查过结果显示的值
  function getTagVal(item: FilterTableItem) {
    if (item.key === 'portfolioIds' && item.value instanceof Array) {
      return item.value.map((el: any) => el.portfolioName)
    } else if (item.value instanceof Array) {
      return item.value.map((str: string) => {
        return enumVal(item.optionItems, item.optionField, str)
      })
    } else {
      return enumVal(item.optionItems, item.optionField, item.value)
    }
  }
  function enumVal(optionItems: any, optionField: any, str: any) {
    if (!optionItems?.length) return str
    let option = optionItems?.find((e: any) => str == e.value)
    return option?.label || str
  }
  function resetAll() {
    filterItem.value.forEach((el: FilterTableItem) => {
      if (el.key === 'currencyCode') {
        el.value = ref('USD')
      } else if (el.key === 'date') {
        el.value = ref(getStartAndEndTime('last_30_days'))
      } else {
        el.value = ref()
      }
    })
    setSearchVal()
  }
  function delTag(data: any) {
    let index = filterItem.value.findIndex((el: FilterTableItem) => el.key == data.key)
    filterItem.value[index].value = ref()
    setSearchVal()
  }
</script>
<style lang="less" scoped>
  .filter-item {
    margin-right: 8px;
    margin-bottom: 5px;
  }
  .filter-result {
    margin-bottom: 5px;
  }
  .filter-list {
    flex-wrap: wrap;
  }
  .time-w {
    color: #999;
    padding: 15px;
    font-size: 12px;
  }
  .chart-wrap {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
